﻿using System;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace Common.Com.TCP
{
    public class TcpClient
    {
     
        /// <summary>
        /// 把对象转换成为C++可以序列化的字节流(如果是和C#通信则用IO.Stream里面的SerializeBinary序列化方法)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] StructToBytes(Object obj)
        {
            int size = Marshal.SizeOf(obj);
            byte[] bytes = new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(obj, structPtr, false);
            Marshal.Copy(structPtr, bytes, 0, size);
            Marshal.FreeHGlobal(structPtr);
            //fixed (byte* pb = &bytes[0])
            //{
            //    Marshal.StructureToPtr(obj, new IntPtr(pb), true);
            //}
            return bytes;
        }

        public static object BytesToStruce(byte[] bytes, Type type)
        {
            //得到结果的大小
            int size = Marshal.SizeOf(type);
            if (size > bytes.Length)
            {
                return null;
            }
            //分配结构大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷贝到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构
            return obj;
        }
    }
}
